<template>
    <div class="ckEditor-wrapper flexC" v-if="isShow">
        <textarea :id="id">
            This is my textarea to be replaced with CKEditor.
        </textarea>
    </div>
</template>

<script>
    let self
    export default {
        name: "ckEditor-wrapper",
        props: [
            'value'
        ],
        data() {
            self = this
            return {
                id: null,
                ckeditor: null,
                isShow: false
            }
        },
        created() {
        },
        mounted() {

        },
        methods: {
            showEdit(status){
                this.isShow = status
                if(status) {
                    this.ckeditor = null
                    this.id = 'ck'+parseInt(Math.random() * 10000).toString()
                    this.$nextTick(()=>{
                        this.init()
                    })
                } else {
                    this.ckeditor = null
                }
            },
            init(){
                let userInfo = JSON.parse(sessionStorage.getItem('userData'))
                // 渲染编辑器
                self.ckeditor = window.CKEDITOR.replace(self.id,{
                    language: 'zh-cn',
                    // 图片上传的配置
                    fileTools_requestHeaders: {
                        'apiAuth': userInfo.apiAuth,
                        'userid': userInfo.id,
                        'username': userInfo.username,
                    },
                    //粘贴图片时用得到
                    uploadUrl: this.$baseUrl + 'CmsContentList/upload',

                    filebrowserBrowseUrl: location.origin+'/#/cms/imglist', // 图片文件预览地址
                    // filebrowserImageBrowseUrl: 'https://ckeditor.com//apps/ckfinder/3.4.5/ckfinder.html?type=Images',
                    // filebrowserUploadUrl: this.$baseUrl + 'CmsContentList/fileUpload',
                    filebrowserImageUploadUrl: this.$baseUrl + 'CmsContentList/upload',
                    // 图片上传的配置 end
                    // embed_provider: '//iframe.ly/api/oembed?url={url}&callback={callback}&api_key=44e5dc002a048d3a98db27'  //配置视频资源的地址，这里配置的是iframely的api地址

                })

                // 设置初始内容
                self.ckeditor.setData(self.value)

                // 监听内容变更事件
                self.ckeditor.on('change', function() {
                    self.$emit('input', self.ckeditor.getData())
                })
            }
        },
        watch: {
            // 监听prop的变化，更新ckeditor中的值
            value: function() {
                if(this.ckeditor !== null) {
                    if (this.value !== this.ckeditor.getData()) {
                        this.ckeditor.setData(this.value)
                    }
                }
            }
        },
        // 销毁组件前，销毁编辑器
        beforeDestroy: function() {
            self.ckeditor = null
        },
        filters: {}
    }
</script>

<style lang="less">
    .ckEditor-wrapper {

    }
</style>